package com.itheima.quartz;

import java.io.Serializable;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 发送邮件工具类
 */
public class MailUtils implements Serializable
{
    /**
     * 获取邮箱会话
     */
    public static Session getMailSession(final Properties mailProps){
        try
        {
           
            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator()
            {
                protected PasswordAuthentication getPasswordAuthentication()
                {
                    // 用户名、密码
                    String userName = mailProps.getProperty("mail.username");
                    String password = mailProps.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };
            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(mailProps, authenticator);
            System.out.println("邮箱登录成功");
            return mailSession;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }
    
    /**
     * 发送邮件
     * @param subject  邮件标题
     * @param mailSession 邮箱会话
     * @param mailProps 邮箱属性
     * @param sendMessage 需要发送的信息
     * @param toAddress 发送的邮箱地址
     */
    public static void sendMail(String subject,Session mailSession,Properties mailProps,String sendMessage, String toAddress)
    {
        System.out.println("要发邮件了。。。");
        try
        {
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            InternetAddress from = new InternetAddress(mailProps.getProperty("mail.username"));
            message.setFrom(from);
            // 设置收件人
            InternetAddress to = new InternetAddress(toAddress);
            message.setRecipient(RecipientType.TO, to);
            // 设置邮件标题
            message.setSubject(subject);
            // 设置邮件的内容体
            message.setContent(sendMessage, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功。。。");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}
